<template>
  <div class="textarea-input">
    <el-input
      v-model="localValue"
      type="textarea"
      :rows="rows"
      :maxlength="maxLength"
      :placeholder="param.placeholder || `请输入${param.paramName}`"
      :clearable="true"
      :show-word-limit="showWordLimit"
      :disabled="param.disabled"
      resize="vertical"
      @input="handleInput"
      @blur="handleBlur"
    />
  </div>
</template>

<script>
export default {
  name: 'TextareaInput',
  props: {
    param: {
      type: Object,
      required: true
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      localValue: this.value
    }
  },
  computed: {
    // 文本域行数
    rows() {
      return this.param.rows || 3
    },
    
    // 最大长度
    maxLength() {
      return this.param.maxLength || 500
    },
    
    // 是否显示字数统计
    showWordLimit() {
      return this.param.showWordLimit !== false
    }
  },
  watch: {
    value(newVal) {
      this.localValue = newVal
    }
  },
  methods: {
    handleInput(value) {
      const isValid = this.validateText(value)
      const message = isValid ? '' : this.getValidationMessage(value)
      
      this.$emit('change', {
        value: value || '',
        isValid,
        message
      })
    },
    
    handleBlur() {
      // 触发最终验证
      const isValid = this.validateText(this.localValue)
      const message = isValid ? '' : this.getValidationMessage(this.localValue)
      
      if (!isValid) {
        this.$emit('change', {
          value: this.localValue,
          isValid,
          message
        })
      }
    },
    
    validateText(value) {
      if (!value) {
        return !this.param.required
      }
      
      // 必填验证
      if (this.param.required && !value.trim()) {
        return false
      }
      
      // 长度验证
      if (this.param.minLength && value.length < this.param.minLength) {
        return false
      }
      
      if (this.param.maxLength && value.length > this.param.maxLength) {
        return false
      }
      
      // 正则验证
      if (this.param.pattern) {
        const regex = new RegExp(this.param.pattern)
        return regex.test(value)
      }
      
      return true
    },
    
    getValidationMessage(value) {
      if (this.param.required && !value.trim()) {
        return '此项为必填项'
      }
      
      if (this.param.minLength && value.length < this.param.minLength) {
        return `内容长度不能少于${this.param.minLength}个字符`
      }
      
      if (this.param.maxLength && value.length > this.param.maxLength) {
        return `内容长度不能超过${this.param.maxLength}个字符`
      }
      
      if (this.param.pattern && !new RegExp(this.param.pattern).test(value)) {
        return this.param.validationMessage || '格式不正确'
      }
      
      return '输入内容无效'
    }
  }
}
</script>

<style scoped>
.textarea-input {
  width: 100%;
}
</style>